<template>
  <ContentWrap>
    <!-- Tabs 标签页 -->
    <el-tabs v-model="activeTab" class="mb-4" @tab-change="handleTabChange">
      <el-tab-pane label="供应商报价" name="offer" />
      <el-tab-pane label="产品图片" name="picture" />
      <el-tab-pane label="检测COA单" name="orders" />
    </el-tabs>

    <!-- 如果当前选中的是供应商报价 offer，展示列表和按钮 -->
    <template v-if="activeTab === 'offer'">
      <!-- 操作按钮 -->
      <el-row>
        <el-col :span="24">
          <el-form-item>
            <el-button
              type="primary"
              v-hasPermi="['business:supplier-info:create']"
              @click="openForm('create')"
            >
              新增
            </el-button>
            <el-button
              type="primary"
              v-hasPermi="['business:supplier-info:update']"
              @click="handleEdit"
              :disabled="selectedRows.length !== 1"
            >
              编辑
            </el-button>
            <el-button
              type="primary"
              v-hasPermi="['business:supplier-info:delete']"
              @click="handleDeleteSelected"
              :disabled="selectedRows.length === 0"
            >
              删除
            </el-button>
          </el-form-item>
        </el-col>
      </el-row>

      <!-- 表格 -->
      <el-table
        v-loading="loading"
        :data="list"
        :stripe="true"
        :show-overflow-tooltip="true"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column label="供应商名称" align="center" prop="supplierName" />
        <el-table-column label="供应商分类" prop="supplierType" align="center">
          <template #default="scope">
            <span class="link-type" @click="handleTypeClick(scope.row)">
              {{ scope.row.supplierType }}
            </span>
          </template>
        </el-table-column>
        <el-table-column label="数量" align="center" prop="num" />
        <el-table-column label="单位" align="center" prop="unit" />
        <el-table-column label="产品型号" align="center" prop="model" />
        <el-table-column label="单价" align="center">
          <template #default="scope">
            ¥{{ scope.row.price.toFixed(2) }}
          </template>
        </el-table-column>
        <el-table-column label="总金额" align="center">
          <template #default="scope">
            ¥{{ scope.row.amount.toFixed(2) }}
          </template>
        </el-table-column>
        <el-table-column label="报价时间" align="center">
          <template #default="scope">
            {{ dateFormatter(scope.row.createTime) }}
          </template>
        </el-table-column>
        <el-table-column label="报价有效期" align="center" prop="validity" />
        <!-- <el-table-column label="操作" align="center" width="120">
          <template #default="scope">
            <el-button
              link
              type="primary"
              @click="openForm('update', scope.row.id)"
              v-hasPermi="['business:supplier-info:update']"
            >
              编辑
            </el-button>
            <el-button
              link
              type="danger"
              @click="handleDelete(scope.row.id)"
              v-hasPermi="['business:supplier-info:delete']"
            >
              删除
            </el-button>
          </template>
        </el-table-column> -->

        <template #empty>
          <div v-if="loading">数据加载中...</div>
          <div v-else>暂无数据</div>
        </template>
      </el-table>
      <Pagination
        :total="total"
        v-model:page="queryParams.pageNo"
        v-model:limit="queryParams.pageSize"
        @pagination="handlePaginationChange" 
      />
    </template>

    <!-- 如果是其他 tab（如产品图片、COA单），加载对应组件 -->
    <component :is="currentTabComponent" v-bind="tabProps" v-else />
  </ContentWrap>

  <!-- 表单弹窗 -->
  <SupplierInfoForm 
      ref="formRef" 
      @success="handleQuoteAdded"
    />
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted } from 'vue'
import { dateFormatter } from '@/utils/formatTime'
import { getSupplierQuotePage } from '@/api/product/supplierinfo'
import download from '@/utils/download'
import { SupplierInfoApi, SupplierInfoVO } from '@/api/product/supplierinfo'
import SupplierInfoForm from './SupplierInfoForm.vue'
import prodpicture from '@/views/product/prodpicture/index.vue'
import { useRoute } from 'vue-router'
import { ElMessageBox, ElMessage } from 'element-plus'
import { useI18n } from 'vue-i18n'

const { t } = useI18n() // 国际化
const route = useRoute() // 获取传参对象

// 产品ID
const productId = ref<number | null>(null)

// 传递到表单的产品信息
const passedProductInfo = ref({
  id: null,
  productName: '',
  productEnName: '',
  productSpec: ''
})

// 处理报价添加成功事件
const handleQuoteAdded = () => {
  console.log('供应商报价添加成功，刷新列表')
  getList() // 刷新数据
}

// 组件名称
defineOptions({ name: 'SupplierInfo' })

// 当前激活的标签页
const activeTab = ref('offer')

// 选中的行
const selectedRows = ref<SupplierQuoteRespVO[]>([]) 

// 处理选中行变化
const handleSelectionChange = (selection: SupplierQuoteRespVO[]) => {
  selectedRows.value = selection
  const selectedIds = selection.map(item => item.id)
  console.log('选中的ID:', selectedIds)
}

// 报价记录接口定义
interface SupplierQuoteRespVO {
  id: number
  supplierId: number
  supplierName: string
  supplierType: string
  num: number
  unit: string
  model: string
  price: number
  amount: number
  createTime: number
  validity: string
}

// 处理分页变化
const handlePaginationChange = (pagination: { page: number; limit: number }) => {
  queryParams.pageNo = pagination.page
  queryParams.pageSize = pagination.limit
  getList()
}

// 组件映射逻辑
const currentTabComponent = computed(() => {
  switch (activeTab.value) {
    case 'picture':
      return prodpicture
    case 'orders':
      return null
    default:
      return null
  }
})

// 标签页属性
const tabProps = computed(() => {
  if (activeTab.value === 'picture') {
    return {
      productInfo: {
        prodId: route.query.id,
        name: route.query.name,
        nameEn: route.query.nameEn,
        specs: route.query.specs
      }
    }
  }
  return {}
})

// 处理标签页切换
const handleTabChange = (tabName: string) => {
  console.log('切换到标签页:', tabName)
}

// 加载状态
const loading = ref(true) 
// 列表数据
const list = ref<SupplierQuoteRespVO[]>([])
// 总记录数
const total = ref(0) 
// 查询参数
const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  productId: undefined as number | undefined,
})
// 表单引用
const formRef = ref()

/** 查询列表 */
const getList = async () => {
  loading.value = true
  try {
    const params = {
      pageNo: queryParams.pageNo,
      pageSize: queryParams.pageSize,
      productId: queryParams.productId
    }
    
    const res = await getSupplierQuotePage(params)
    if (res) {
      list.value = res.list || []
      total.value = res.total || 0
    }
    console.log('获取数据成功:', res)
  } catch (error) {
    console.error('获取数据失败:', error)
    ElMessage.error('获取数据失败，请重试')
  } finally {
    loading.value = false
  }
}

/** 添加/修改操作 */
const openForm = (type: string, id?: number) => {
  formRef.value.open(type, id, passedProductInfo.value)
}

/** 编辑操作 */
const handleEdit = () => {
  if (selectedRows.value.length !== 1) {
    ElMessage.warning('请选择一条要编辑的记录')
    return
  }
  const id = selectedRows.value[0].id
  console.log("编辑时id内容:", id)
  openForm('update', id)
}

/** 删除单个记录 */
/** 删除单个记录 */
const handleDelete = async (id: number) => {
  try {
    await ElMessageBox.confirm('确定要删除该报价记录吗?', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    // 发起删除
    const loading = ElLoading.service({
      lock: true,
      text: '删除中...',
    })
    
    try {
      await SupplierInfoApi.deleteSupplierQuote(id)
      ElMessage.success('删除成功')
      // 刷新列表
      getList()
    } catch (error) {
      console.error('删除失败:', error)
      ElMessage.error('删除失败，请重试')
    } finally {
      loading.close()
    }
  } catch (error) {
    console.log('删除取消')
  }
}

/** 批量删除 */
const handleDeleteSelected = async () => {
  if (selectedRows.value.length === 0) {
    ElMessage.warning('请选择要删除的记录')
    return
  }
  
  try {
    await ElMessageBox.confirm(`确定要删除选中的 ${selectedRows.value.length} 条记录吗?`, '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    // 获取所有选中记录的ID
    const ids = selectedRows.value.map(item => item.id)
    
    const loading = ElLoading.service({
      lock: true,
      text: `正在删除 ${ids.length} 条记录...`,
    })
    
    try {
      // 发起批量删除
      await SupplierInfoApi.batchDeleteSupplierQuote(ids)
      console.log('前端删除的ids',ids)
      ElMessage.success(`成功删除 ${ids.length} 条记录`)
      
      // 刷新列表
      getList()
      // 清空选中
      selectedRows.value = []
    } catch (error) {
      console.error('批量删除失败:', error)
      ElMessage.error('批量删除失败，请重试')
    } finally {
      loading.close()
    }
  } catch (error) {
    console.log('批量删除取消')
  }
}

/** 初始化 **/
onMounted(() => {
  // 从路由参数获取产品ID
  const idFromRoute = route.query.id
  if (idFromRoute) {
    const id = Number(idFromRoute)
    if (!isNaN(id)) {
      productId.value = id
      queryParams.productId = id
      
      // 保存传递到表单的产品信息
      passedProductInfo.value = {
        id: id,
        productName: route.query.name as string || '',
        productEnName: route.query.nameEn as string || '',
        productSpec: route.query.specs as string || ''
      }
    }
  }

  getList()
})
</script>

<style scoped>
.choose-btn-box {
  margin-top: 20px;
  text-align: center;
}

.footer-btns {
  position: absolute;
  bottom: 20px;
  right: 20px;
}

.link-type {
  color: #409eff;
  cursor: pointer;
}

.link-type:hover {
  text-decoration: underline;
}

.el-button--link {
  padding: 0;
  margin: 0 5px;
}
</style>